package com.jinzhi.jzweb.controller;


import java.io.*;
import java.text.ParseException;
import java.util.*;

import com.jinzhi.api.exception.IFastApiException;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.type.ApiEnumError;
import com.jinzhi.jzapi.utils.HttpClientUtil;
import com.jinzhi.jzweb.domain.CertificationBatchDO;
import com.jinzhi.jzweb.pojo.CertificatesExportVo;
import com.jinzhi.jzweb.pojo.CertificatesVo;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.jzweb.utils.ValuesUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.jzweb.domain.MemberApplyDO;
import com.jinzhi.jzweb.service.MemberApplyService;
import com.jinzhi.common.utils.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <pre>
 * 成员申请表
 * </pre>
 * <small> 2024-06-18 11:09:22 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/memberApply")
public class MemberApplyController extends BaseController {
    @Autowired
    private MemberApplyService memberApplyService;
    @Autowired
    private DictService dictService;

    @GetMapping()
//    @RequiresPermissions("jzweb:memberApply:memberApply")
    String MemberApply() {
        return "jzweb/memberApply/memberApply";
    }




    @ResponseBody
    @GetMapping("/list")
//    @RequiresPermissions("jzweb:memberApply:memberApply")
    public Result<Page<MemberApplyDO>> list(MemberApplyDO memberApplyDTO) {
        // 查询列表数据
        Page<MemberApplyDO> page = memberApplyService.selectPage(getPage(MemberApplyDO.class),
                memberApplyService.convertToEntityWrapper().orderBy("id", false));
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            MemberApplyDO obj = (MemberApplyDO) page.getRecords().get(i);
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }

    @GetMapping("/details/{id}")
//    @RequiresPermissions("jzweb:memberApply:add")
    String details(@PathVariable("id") Long id, Model model) {
        MemberApplyDO memberApply = memberApplyService.selectById(id);
        model.addAttribute("memberApply", memberApply);
        return "jzweb/memberApply/details";
    }

    @GetMapping("/edit/{id}")
//    @RequiresPermissions("jzweb:memberApply:edit")
    String edit(@PathVariable("id") Long id, Model model) {
        MemberApplyDO memberApply = memberApplyService.selectById(id);
        model.addAttribute("memberApply", memberApply);
        return "jzweb/memberApply/edit";
    }

    @Log("添加成员申请表")
    @ResponseBody
    @PostMapping("/save")
//    @RequiresPermissions("jzweb:memberApply:add")
    public Result<String> save(MemberApplyDO memberApply) {
        memberApplyService.insert(memberApply);
        return Result.ok();
    }

    @Log("修改成员申请表")
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("jzweb:memberApply:edit")
    public Result<String> update(MemberApplyDO memberApply) {
        boolean update = memberApplyService.updateById(memberApply);
        return update ? Result.ok() : Result.fail();
    }

    @Log("删除成员申请表")
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("jzweb:memberApply:remove")
    public Result<String> remove(Long id) {
        memberApplyService.deleteById(id);
        return Result.ok();
    }

    @Log("批量删除成员申请表")
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("jzweb:memberApply:batchRemove")
    public Result<String> remove(@RequestParam("ids[]") Long[] ids) {
        memberApplyService.deleteBatchIds(Arrays.asList(ids));
        return Result.ok();
    }


    /**
     * 申请管理列表查询
     *
     * @return
     */
    @GetMapping("/selMemberApplyList")
    @ResponseBody
    public Result<Page<MemberApplyDO>> selMemberApplyList(@RequestParam(value = "unitType", required = false) Integer unitType,
                                                          @RequestParam(value = "name", required = false) String name,
                                                          @RequestParam("current") int current,
                                                          @RequestParam("size") int size,
                                                          @RequestParam(value = "checkStatus", required = false) Integer checkStatus,
                                                          @RequestParam(value = "checkResult", required = false) Integer checkResult
    ) {

        return memberApplyService.selMemberApplyList(unitType, name, current, size, checkStatus, checkResult);
    }

    /**
     * 证书管理列表查询
     *
     * @return
     */
    @GetMapping("/selCertificateList")
    @ResponseBody
    public Result<Page<MemberApplyDO>> selCertificateList(@RequestParam(value = "unitType", required = false) Integer unitType,
                                                          @RequestParam(value = "name", required = false) String name,
                                                          @RequestParam("current") int current,
                                                          @RequestParam("size") int size,
                                                          @RequestParam(value = "status", required = false) Integer status,
                                                          @RequestParam(value = "intention", required = false) Integer intention
    ) {

        return memberApplyService.selCertificateList(unitType, name, current, size, status, intention);
    }

    /**
     * 审核
     *
     * @return
     */
    @GetMapping("/checkMemberApply")
    @ResponseBody
    public Result<?> checkMemberApply(@RequestParam("id") Long id,
                                           @RequestParam("reason") String reason,
                                           @RequestParam("checkResult") Integer checkResult
    ) {
        return  memberApplyService.checkMemberApply(id,reason,checkResult);

    }

    /**
     * 逻辑删除申请管理
     *
     * @return
     */
    @PostMapping("/removeById")
    @ResponseBody
    public Result<String> removeById(Long id) {
        MemberApplyDO memberApplyDO = memberApplyService.selectById(id);
        memberApplyDO.setIsDelete(1);
        memberApplyService.updateById(memberApplyDO);
        return Result.ok();
    }

    /**
     * 证书删除
     *
     * @return
     */
    @PostMapping("/removeCertificate")
    @ResponseBody
    public Result<String> removeCertificate(Long id) {
        MemberApplyDO memberApplyDO = memberApplyService.selectById(id);
        memberApplyDO.setStatus(0);
        memberApplyDO.setPersonalEmployment("");
        memberApplyDO.setPersonalStatus(2);
        memberApplyDO.setUnitStatus(2);
        memberApplyDO.setUnitEmployment("");
        memberApplyService.updateById(memberApplyDO);
        return Result.ok();
    }

    /**
     * 修改申请信息
     *
     * @return
     */
    @ResponseBody
    @PostMapping("/updateMemberApply")
    public Result<?> updateMemberApply(@RequestBody MemberApplyDO cond) throws ParseException {

        return memberApplyService.updateMemberApply(cond);
    }

    /**
     * 导出申请信息
     *
     * @param response
     */
    @Log("导出申请信息")
    @RequestMapping("/downloadMemberApply")
    @ResponseBody
    public Result<?> downloadMemberApply(HttpServletRequest request, HttpServletResponse response) {
        return memberApplyService.downloadMemberApply(response);

    }

    /**
     * 申请详情
     *
     * @return
     */
    @GetMapping("/getInfo")
    @ResponseBody
    public Result<?> getInfo(@RequestParam("id") Long id) {
        MemberApplyDO memberApplyDO = memberApplyService.getInfo(id);
        return Result.ok(memberApplyDO);
    }

    /**
     * 批量生成
     *
     * @return
     */
    @GetMapping("/getCertificateList")
    @ResponseBody
    public Result<?> getCertificateList(@RequestParam(value = "ids",required = false) List<Long> ids) {
        //查询模板单位聘书
        String unitTraSynthesis = dictService.selDicBy(selThetemplate("0"));
        if (StringUtils.isNotBlank(unitTraSynthesis)) {
            unitTraSynthesis = ValuesUtil.localUrl + unitTraSynthesis;
        }
        System.out.println("单位模板地址为++++++++++++++++++++++++++++++++++++++++++++++++++++"+unitTraSynthesis);
        //查询模板个人聘书
        String personalTraSynthesis = dictService.selDicBy(selThetemplate("1"));
        if (StringUtils.isNotBlank(personalTraSynthesis)) {
            personalTraSynthesis = ValuesUtil.localUrl + personalTraSynthesis;
        }
        System.out.println("个人模板地址为++++++++++++++++++++++++++++++++++++++++++++++++++++"+personalTraSynthesis);
        //第五步--获取电子公章
        String electronic = getElectronic();
        System.out.println("电子公章地址为++++++++++++++++++++++++++++++++++++++++++++++++++++"+electronic);
        memberApplyService.getCertificateList(ids,unitTraSynthesis,personalTraSynthesis,electronic);
        return Result.ok();

    }


    /**
     * 导出单位证书PDF文件
     */
    @Log("导出单位证书PDF文件")
    @RequestMapping("/exportUnitPdf")
//    @RequiresPermissions("jzweb:trainingCertificates:import")
    @ResponseBody
    public void exportUnitPdf(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "ids",required = false) List<Long> ids){
        try {
            memberApplyService.exportUnitPdf(ids,response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 导出个人证书PDF文件
     */
    @Log("导出个人证书PDF文件")
    @RequestMapping("/exportPersonalPdf")
//    @RequiresPermissions("jzweb:trainingCertificates:import")
    @ResponseBody
    public void exportPersonalPdf(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "ids",required = false) List<Long> ids){
        try {
            memberApplyService.exportPersonalPdf(ids,response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 下载PDF文件
     */
    @Log("下载PDF文件")
    @RequestMapping("/exportPdf")
    @ResponseBody
    public void exportPdf(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "id",required = false) Long id){
        try {
            memberApplyService.exportPdf(id,response);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }
    /**
     * 重新生成证书
     */
    @Log("重新生成证书")
    @GetMapping("/getCertificate")
    @ResponseBody
    public Result<?> getCertificate(@RequestParam(value = "id") Long id) {
        //查询模板单位聘书
        String unitTraSynthesis = dictService.selDicBy(selThetemplate("0"));
        if (StringUtils.isNotBlank(unitTraSynthesis)) {
            unitTraSynthesis = ValuesUtil.localUrl + unitTraSynthesis;
        }
        System.out.println("单位模板地址为++++++++++++++++++++++++++++++++++++++++++++++++++++"+unitTraSynthesis);
        //查询模板个人聘书
        String personalTraSynthesis = dictService.selDicBy(selThetemplate("1"));
        if (StringUtils.isNotBlank(personalTraSynthesis)) {
            personalTraSynthesis = ValuesUtil.localUrl + personalTraSynthesis;
        }
        System.out.println("个人模板地址为++++++++++++++++++++++++++++++++++++++++++++++++++++"+personalTraSynthesis);
        //第五步--获取电子公章
        String electronic = getElectronic();
        System.out.println("电子公章地址为++++++++++++++++++++++++++++++++++++++++++++++++++++"+electronic);
        memberApplyService.getCertificate(id,unitTraSynthesis,personalTraSynthesis,electronic);
        return Result.ok();

    }

    private Map selThetemplate( String certificatesType) {
        Map map = new HashMap();
        if (certificatesType.equals("0")) {
            map.put("name", "单位聘书证书");
            //todo
            map.put("type", "danweizhenshu");
        }
        if (certificatesType.equals("1")) {
            map.put("name", "个人聘书证书");
            //todo
            map.put("type", "grenpinshu");
        }
        return map;
    }

    //获取电子公章
    private String getElectronic(){
        String electronicSeal = null;
        //获取电子公章
        Map map = new HashMap();
        map.put("name", "金职电子公章");
        map.put("type", "electronic_seal");
        electronicSeal = dictService.selDicBy(map);
        if (StringUtils.isNotBlank(electronicSeal)) {
            electronicSeal = ValuesUtil.localUrl + electronicSeal;
        }
        return electronicSeal;
    }

}
